package com.tgy.demo;

import com.tgy.demo.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/***
 * @ClassName: trans
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 17:49 2021/11/30
 * @version : V1.0
 */
public class trans {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement st = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            //关闭数据库的自动提交,会自动开启事务
            connection.setAutoCommit(false);

            String sql1 = "update account set money = money-100 where name = 'A'";
            st = connection.prepareStatement(sql1);
            st.executeUpdate();

            int x = 1/0; //报错

            String sql2 = "update account set money = money+100 where name = 'B'";

            st = connection.prepareStatement(sql2);
            st.executeUpdate();


            //业务完毕，提交事务
            connection.commit();
            System.out.println("成功！");

        } catch (SQLException throwables) {
            //失败默认回滚
/*            try {
                //如果失败则回滚
                connection.rollback();
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            throwables.printStackTrace();
        }
    }
}
